import random
import time

import cv2
import mss
import numpy as np

import scene
import action

area = {"left": 1080, "top": 308, "width": 418, "height": 780}

cate_index = 0
is_cate_init = False
row_sku_index = 0

with mss.mss() as sct:
    while True:
        cut_main = sct.grab(area)
        cut_main = np.array(cut_main)
        # 转成灰度，更快查找
        cut_main_gray = cv2.cvtColor(cut_main, cv2.COLOR_BGR2GRAY)

        # 判断当前场景
        scene_now = scene.getscene(cut_main_gray)
        if scene_now != '未知':
            print('当前场景为: ', scene_now)

        if scene_now == '分类':
            if cate_index > 57:
                print('finish')
            else:
                if action.clickCate(cut_main_gray, cate_index):
                    is_cate_init = True
                    print("当前第" + str(cate_index) + '个分类')
                    cate_index += 1
                else:
                    action.moveTo(260, 542)
                    action.scroll(-100)
                    time.sleep(0.5)
        elif scene_now == '商品列表':
            time.sleep(random.randint(2, 5))
            if is_cate_init:
                print('首次跳过')
                is_cate_init = False
            else:
                if row_sku_index < 2:
                    while not action.clickGoods(cut_main_gray, row_sku_index):
                        print('重试')
                    row_sku_index += 1
                else:
                    row_sku_index = 0
                    action.moveTo(260, 542)
                    action.scroll(-415)
            time.sleep(1)
        elif scene_now == '没有商品':
            action.click(cut_main_gray, 'back')
        elif scene_now == '浏览完毕':
            time.sleep(random.randint(2, 5))
            if row_sku_index < 2:
                action.clickGoods(cut_main_gray, row_sku_index)
                row_sku_index += 1
            else:
                row_sku_index = 0
                action.click(cut_main_gray, 'back')
            time.sleep(1)
        elif scene_now == '商品详情':
            action.moveTo(260, 542)
            time.sleep(random.randint(1, 3))
            action.scroll(-2000)
            time.sleep(1)
            action.scroll(-2000)
            time.sleep(1)
            action.click(cut_main_gray, 'back1')
        elif scene_now == '缺货':
            action.click(cut_main_gray, 'closenotbuy')
        elif scene_now == '断开':
            action.click(cut_main_gray, 'retry')
            time.sleep(1)

        # 调用opencv的imgshow方法显示图片
        cv2.imshow("tms", cut_main)
        # 等待按键关闭窗口，否则直接会退出
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        # 等待5ms，用户输入q退出
        if cv2.waitKey(5) & 0xFF == ord("q"):
            cv2.destroyAllWindows()
            break
